<template>
    <div>
        <div class="page-body">
            <div v-loading="xwfxLoading">
                <div class="page-header-top">
                    <div class="page-header-top-title">
                        用户行为分析
                    </div>
                    <el-radio-group v-model="xwfx_dateSelect" @change="onXwfxSelect">
                        <el-radio-button v-for="item in xwfx_dateList" :label="item.code">{{ item.name }}</el-radio-button>
                    </el-radio-group>
                    <div style="margin-left: 10px;">
                        <el-date-picker :clearable="false" v-model="xwfx_dateShow" type="daterange" range-separator="至"
                            start-placeholder="开始日期" end-placeholder="结束日期" :disabled-date="disabledDate"
                            @change="onWxfxDateChange" />
                    </div>
                    <div style="color:rgba(0, 0, 0, 0.5);padding-left: 10px;">每天10:00 更新昨日数据</div>
                </div>
                <div class="page-header">
                    <div class="page-header-left">
                        <div class="page-header-item" :class="{
                            'page-header-item-show': xwfx_card_index == key
                        }" v-for="(item, key) in xwfx_showdata" @click="onClickXwfxCard(key)">
                            <div class="page-header-item-title">{{ item.name }}
                                <el-tooltip class="box-item" effect="dark" placement="top">
                                    <template #content> <span v-html="item.line"></span> </template>
                                    <svg style="width: 15px;" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"
                                        data-v-ea893728="">
                                        <path fill="currentColor"
                                            d="M512 64a448 448 0 1 1 0 896 448 448 0 0 1 0-896m23.744 191.488c-52.096 0-92.928 14.784-123.2 44.352-30.976 29.568-45.76 70.4-45.76 122.496h80.256c0-29.568 5.632-52.8 17.6-68.992 13.376-19.712 35.2-28.864 66.176-28.864 23.936 0 42.944 6.336 56.32 19.712 12.672 13.376 19.712 31.68 19.712 54.912 0 17.6-6.336 34.496-19.008 49.984l-8.448 9.856c-45.76 40.832-73.216 70.4-82.368 89.408-9.856 19.008-14.08 42.24-14.08 68.992v9.856h80.96v-9.856c0-16.896 3.52-31.68 10.56-45.76 6.336-12.672 15.488-24.64 28.16-35.2 33.792-29.568 54.208-48.576 60.544-55.616 16.896-22.528 26.048-51.392 26.048-86.592 0-42.944-14.08-76.736-42.24-101.376-28.16-25.344-65.472-37.312-111.232-37.312zm-12.672 406.208a54.272 54.272 0 0 0-38.72 14.784 49.408 49.408 0 0 0-15.488 38.016c0 15.488 4.928 28.16 15.488 38.016A54.848 54.848 0 0 0 523.072 768c15.488 0 28.16-4.928 38.72-14.784a51.52 51.52 0 0 0 16.192-38.72 51.968 51.968 0 0 0-15.488-38.016 55.936 55.936 0 0 0-39.424-14.784z">
                                        </path>
                                    </svg>
                                </el-tooltip>
                            </div>
                            <div class="page-header-item-cont">
                                {{ item.count }}
                            </div>
                        </div>
                    </div>
                    <div class="page-header-right">
                        <div class="page-tp" :id="xwfx_id">

                        </div>
                    </div>
                </div>
            </div>

            <div>

            </div>
            <div>

            </div>
        </div>
    </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { uploadSectionFile } from "@/utils/api";
import { request } from "@/utils/axios";
import { ElMessage } from "element-plus";
export default defineComponent({
    nam: "Home"
})
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive, nextTick } from "vue";
import moment from "@/utils/moment";
import { onMapInit, mapKey } from "@/utils/map";
import { pad, hmzToValue } from "@/utils/base";
import * as echarts from 'echarts';

/**
 * ====================
 * 用户行为分析
 * ====================
 */

/**
 * 展示loading
 */
let xwfxLoading = ref(false);

/**
 * 展示数据
 */
let xwfx_showdata = reactive<{
    [key: string]: {
        name: string,
        line: string,
        count: string,
        list: {
            title: string,
            value: 0
        }[]
    }
}>({
    active_user_num: {
        name: "活跃用户数",
        line: "访问小程序页面的用户数，同一用户多次访问不重复计",
        count: "0",
        list: []
    },
    new_user_num: {
        name: "新增用户数",
        line: "首次访问小程序页面的用户数，同一用户多次访问不重复计",
        count: "0",
        list: []
    },
    avg_stay_time: {
        name: "次均停留时长",
        line: "平均每次打开小程序停留在小程序页面的总时长，<br/> 即时段内所有用户总停留时长 / 总打开次数",
        count: "0",
        list: []
    },
    open_time: {
        name: "打开次数",
        line: "启动小程序的次数",
        count: "0",
        list: []
    },
    per_user_open_time: {
        name: '人均打开次数',
        line: "所选时段内，平均每人打开小程序的总次数，<br/> 即时段内所有用户打开总次数 / 总活跃人数",
        count: "0",
        list: []
    },
    per_user_stay_time: {
        name: "人均停留时长",
        line: "人均停留在小程序页面的总时长，<br/> 即时段内所有用户总停留时长 / 总活跃人数",
        count: "0",
        list: []
    },
    share_time: {
        name: "分享次数",
        line: "点击分享按钮、调起分享框的次数（包含实际未分享的次数）",
        count: "0",
        list: []
    },
    total_user_num: {
        name: "累计用户数",
        line: "所选时段最后一天为止，历史上所有启动过小程序的设备数去重",
        count: "0",
        list: []
    }
})


/**
 * 昨天的日期
 */

let ztDate = moment().subtract(1, 'days').toDate();

/**
 * 列表
 */
let xwfx_dateList = ref([
    {
        code: "-1",
        name: "昨天",
        dateList: [ztDate, ztDate]
    },
    {
        code: "-7",
        name: "近7天",
        dateList: [moment().subtract(7, 'days').toDate(), ztDate]
    },
    {
        code: "-30",
        name: "近30天",
        dateList: [moment().subtract(30, 'days').toDate(), ztDate]
    },
    {
        code: "-60",
        name: "近60天",
        dateList: [moment().subtract(60, 'days').toDate(), ztDate]
    },
    {
        code: "-90",
        name: "近90天",
        dateList: [moment().subtract(90, 'days').toDate(), ztDate]
    },
])

/**
 * 选中
 */
let xwfx_dateSelect = ref(xwfx_dateList.value[0].code);

// console.log(moment().toDate());
// console.log(moment().subtract(1, 'days').valueOf());
/**
 * 展示日期
 * 默认为昨天
 */
let xwfx_dateShow = ref<any>(xwfx_dateList.value[0].dateList);


/**
 * 日期禁用
 */
function disabledDate(Data: any) {
    return moment().isSameOrBefore(Data, "day")
}

/**
 * 更改信息
 */
function onXwfxSelect(value: any) {
    let index = xwfx_dateList.value.findIndex(item => item.code == value);
    if (index >= 0) {
        xwfx_dateShow.value = xwfx_dateList.value[index].dateList;
        getBehavior();
    }
}

/**
 * 日期发生变化
 */
function onWxfxDateChange(value: Date[]) {
    if (value.length == 2) {
        if (moment(ztDate).isSame(value[1], "day")) {
            //看第二个参数是否是昨天
            //可以进行第二部判断
            let dayCount = moment(ztDate).diff(value[0], "day") + 1;
            xwfx_dateSelect.value = `-${dayCount}`;
        } else {
            xwfx_dateSelect.value = `0`;
        }
    };
    getBehavior();
}

/**
 * 获取 用户行为信息
 */
function getBehavior() {
    xwfxLoading.value = true;
    request("/DataAnalysis/Behavior", {
        // "DayOffset": xwfx_dateSelect.value, //昨天、近7天、....。天数偏移量，负数，表示前几天，如果是近90天，则为-90
        "StartDate": moment(xwfx_dateShow.value[0]).format("YYYY-MM-DD"), //范围起。如果DayOffset有负数值，则参数忽略
        "EndDate": moment(xwfx_dateShow.value[1]).format("YYYY-MM-DD") //范围止。如果DayOffset有负数值，则参数忽略
    })
        .then(res => {
            // console.log(res);
            if (res.err_no == 0) {
                let sum = res.data.sum;
                let behaviors = res.data.behaviors;
                // console.log(sum);
                //处理总数据
                for (let x in sum) {
                    let showItem = (xwfx_showdata as any)[x];
                    if (showItem) {
                        if (['per_user_stay_time', 'avg_stay_time'].indexOf(x) >= 0) {
                            //需要更改为毫秒值的
                            showItem.count = hmzToValue(sum[x]);
                        } else {
                            showItem.count = sum[x];
                        }
                        //清理数据中的list 即单个指标的 详细指标
                        showItem.list = [];
                    }
                }
                //处理单个指标的 详细指标
                for (let item of behaviors) {
                    for (let x in item) {
                        let showItem = (xwfx_showdata as any)[x];
                        if (showItem) {
                            showItem.list.push({
                                title: item.time,
                                value: item[x]
                            });
                        }
                    }
                }
                // console.log(xwfx_showdata)
                //更新图表配置
                onClickXwfxCard("active_user_num");
            } else {
                ElMessage.error(res.err_msg);
            }
        })
        .finally(() => {
            xwfxLoading.value = false;
        })
}

/**
 * ------------
 * 图表
 * ------------
 */

/**
 * 选择的卡片数据
 */
let xwfx_card_index = ref('active_user_num');

/**
 * 图表ID
 */
let xwfx_id = ref(`xwfx_${Date.now()}`);

/**
 * 图表配置
 */
let xwfx_dom: echarts.ECharts | null = null;

/**
 * 图表初始化 
 */
function xwfx_init() {
    xwfx_dom = echarts.init(document.getElementById(xwfx_id.value));
}

/**
 * 点击卡片
 */
function onClickXwfxCard(row: any) {
    xwfx_card_index.value = row;
    //更新数据
    wxfx_setOption();
}

/**
 * 更新数据
 */
function wxfx_setOption() {
    if (!xwfx_dom) return;
    let dataList = xwfx_showdata[xwfx_card_index.value].list;
    xwfx_dom.setOption({
        xAxis: {
            type: 'category',
            data: dataList.map(item => item.title)
        },
        yAxis: {
            type: 'value',
            minInterval: 1
        },
        tooltip: {
            trigger: 'axis',
            valueFormatter: (value: number) => {
                if (['per_user_stay_time', 'avg_stay_time'].indexOf(xwfx_card_index.value) >= 0) {
                    return hmzToValue(value)
                } else {
                    return value;
                }
            }
        },
        series: [
            {
                data: dataList.map(item => item.value),
                type: 'line'
            }
        ]
    })
}

onMounted(() => {
    getBehavior();
    nextTick(() => {
        xwfx_init();
    })
})
</script>

<style lang="less" scoped>
.page-body {
    padding: 10px;
    width: 100%;
    height: 100%;
}

.page-header-top {
    background-color: white;
    border-radius: 3px;
    height: 50px;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    padding: 0 10px;
}

.page-header-top-title {
    font-weight: bold;
    margin-right: 10px;
}

.page-header {
    display: flex;
    width: 100%;
    height: 350px;
}

.page-header-left {
    display: grid;
    align-content: flex-start;
    grid-template-columns: 180px 180px;
    row-gap: 10px;
    column-gap: 10px;
    margin-right: 10px;
    flex-shrink: 0;
}

.page-header-item {
    border-radius: 3px;
    padding: 10px;
    height: 80px;
    background-color: white;
}

.page-header-item-show {
    background-color: var(--el-color-primary-light-8);
}

.page-header-item-title {
    font-size: 15px;
    color: rgba(0, 0, 0, 0.5);
}

.page-header-item-cont {
    font-size: 26px;
    font-weight: bold;
    margin-top: 10px;
}

.page-header-right {
    flex-grow: 1;
    background-color: white;
    border-radius: 3px;
    height: 100%;
}

// 图表
.page-tp {
    width: 100%;
    height: 100%;
}
</style>